//
//  WPUserAccountModel.m
//  wobingwoyi
//
//  Created by WGP on 16/8/9.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPUserAccountViewModel.h"
#import "WPUserAccount.h"
#import "JPUSHService.h"

@interface WPUserAccountViewModel ()<UIAlertViewDelegate>

@property(nonatomic,copy)void(^loginHandle)();

@end
@implementation WPUserAccountViewModel

+(instancetype)sharedInstance
{
    static WPUserAccountViewModel *instance  = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc] init];
    });
    return instance;
}

-(instancetype)init
{
    if(self = [super init])
    {
        
        [self loadUserAccount];
        
    }
    return self;
}

/**
 *  用户是否登陆
 *
 *  @return Bool
 */
-(BOOL)userLogin
{
    [self loadUserAccount];
    
    if(_userAccount != nil)
    {
        return YES;
    }
    return NO;
}

-(WPUserAccount *)userAccount
{
    if(!_userAccount)
    {
        [self loadUserAccount];
    }
    return _userAccount;
}

-(void)globalLoginWith:(id)parameters successHandle:(void(^)())successHandle
{
    //            登录
    [self showWithStatus:@"正在登录"];
    
    NSString *url = @"user/login.do";
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        
        [self dismiss];
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        
        if ([responseDic[@"result"] isEqualToString:@"success"])
        {
//            保存用户信息
            WPUserAccount *userAccount = [WPUserAccount yy_modelWithDictionary:responseDic[@"detail"]];
            [userAccount saveUserAccount];
            
//            设置请求头
            NSString *tokenStr = [userAccount.token yy_modelToJSONString];
            [[WPNetWorkManager sharedNetWorkManager].requestSerializer setValue:tokenStr forHTTPHeaderField:@"token"];
            
            //用于绑定Alias的  使用NSString 即可
            [JPUSHService setAlias:[NSString stringWithFormat:@"%zd",userAccount.user.id] callbackSelector:nil object:self];
            
//            成功回调
            successHandle();
            
            //友盟用户使用自有账号登录时统计
            [MobClick profileSignInWithPUID:userAccount.user.account];
        }
        else
        {
            [self showErrorInfoWithStatus:responseDic[@"detail"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self dismiss];
        if (error)
        {
            [self showErrorInfoWithStatus:@"登录失败"];
        }
    }];
    

}

#pragma mark - 私有的归档解档方法

-(void)saveUserAccount:(WPUserAccount *)userAccount
{
    
    [NSKeyedArchiver archiveRootObject:userAccount toFile:filepath];
    //    HMLog(@"%@",filepath);
    
    
}

-(void)loadUserAccount
{
    _userAccount = [NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
}

-(void)loginTipWith:(void(^)())loginHandle
{
    self.loginHandle = loginHandle;
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
    [alertView show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        self.loginHandle();
    }
}

//词典转换为字符串

- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

@end
